/*
 * @Author: Lin Hongwei
 * @Date: 2022-10-24 22:56:35
 * @LastEditTime: 2022-10-29 15:33:29
 * @LastEditors: Lin Hongwei
 * @email: 1365755396@qq.com
 * @CSDN: https://blog.csdn.net/weixin_45429409
 * @Description: 登录token校验
 */
const { verify } = require('jsonwebtoken');
const { TOKEN_KEY } = require('../utils/constant');
const { tokenExpiredError, invalidToken } = require('../utils/errType');
const AuthMiddleware = (uless = []) => {
  if (!Array.isArray(uless)) throw new Error("过滤路由配置项需要为数组!");
  return (ctx, next) => {
    const flag = uless.some(item => {
      const reg = new RegExp(item)
      return reg.test(ctx.url)
    });
    if (flag) return next();
    try {
      const token = ctx.headers.token;
      const res = verify(token, TOKEN_KEY);
      ctx.state.user = res;
      return next();
    } catch (err) {
      if (err.name == "TokenExpiredError") return ctx.fail(tokenExpiredError);
      return ctx.fail(invalidToken);
      // switch (err.name) {
      //   case "TokenExpiredError":

      //     break;
      //   case "JsonWebTokenError":
      //     break;
      //   default:
      //     break;
      // }
    }
  }
}

module.exports = AuthMiddleware
